﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;

using Seven.Entity;
using Seven.DataModel.ViewModels.WorkflowAbout;
using Seven.Tools.Extension;
using Seven.Tools.Helper;

namespace Seven.Service.Powerful
{
    public partial class WfFormTypeService
    {
        #region 获取ViewModel

        /// <summary>
        /// 根据父级类别ID获取新的表单类别模型
        /// </summary>
        /// <param name="parentId">父级类别ID</param>
        /// <returns></returns>
        public FormTypeModel GetNewModel(int parentId)
        {
            var model = new FormTypeModel();
            model.ParentID = parentId;
            if (model.ParentID != default(int))
            {
                FormTypeModel parent = this.GetEditModel(model.ParentID);
                model.CompanyID = parent.CompanyID;
                model.CompanyName = parent.CompanyName;
                model.ParentName = parent.Name;
            }
            else
            { model.ParentName = "根目录"; }

            return model;
        }

        /// <summary>
        /// 根据表单类别ID获取供编辑的数据模型
        /// </summary>
        /// <param name="id">表单类别ID</param>
        /// <returns></returns>
        public FormTypeModel GetEditModel(int id)
        {
            using (var unit = DbFactory.UnitOfWork)
            {
                var rep = unit.WfFormType;
                var model = rep.GetEditModelByID(id);
                model.ParentName = model.ParentID == 0 ? "根目录" : rep.GetFormTypeName(model.ParentID);

                return model;
            }
        }

        #endregion

        #region 提供json数据

        /// <summary>
        /// 根据父级ID获取下级表单类型数据
        /// </summary>
        /// <param name="id">父级ID</param>
        /// <param name="filter">是否根据当前用户的管理范围过滤</param>
        /// <returns></returns>
        public JsonResult FormTypeJson(int id, bool filter)
        {
            IEnumerable<WfFormType> data; IEnumerable<KeyValuePair<int, int>> count;
            using (var unit = DbFactory.UnitOfWork)
            {
                var rep = unit.WfFormType;
                data = rep.GetSons(id);
                var Temp = data.Select(s => s.ID);
                count = rep.GetSonsCount(Temp).Where(w => w.Value > 0);
            }
            if (filter && id == 0)
            {
                IEnumerable<int> companyIds = CurrentUserCompanyRange.Select(s => s.ID);
                data = data.Where(w => companyIds.Contains(w.CompanyID));
            }

            return new DataResult(data.Select(s => new
            {
                id = s.ID,
                text = s.Name,
                state = (count.Any(a => a.Key == s.ID) ? "closed" : "open")
            })).SerializeToJsonResult();
        }

        #endregion

        #region CUD操作

        /// <summary>
        /// 保存表单类型
        /// </summary>
        /// <param name="model">表单类型数据模型</param>
        /// <returns></returns>
        public JsonResult SaveFormType(FormTypeModel model)
        {
            WfFormType entity;
            if (model.ID == 0)
            {
                entity = model.CopyTo<WfFormType>();

                using (var unit = DbFactory.UnitOfWork)
                {
                    try
                    {
                        unit.BeginTransaction();
                        unit.WfFormType.EntityAdded(entity);
                        var msg = new string[] { "添加成功!", "添加失败!" };
                        var result = new OperationResult(unit.Commit() > 0, msg);
                        if (result.Success)
                        {
                            result.Data = new
                            {
                                state = "insert",
                                newObj = new
                                {
                                    id = entity.ID,
                                    text = entity.Name,
                                    attributes = new { ParentID = entity.ParentID }
                                }
                            };
                        }
                        return result.SerializeToJsonResult();
                    }
                    catch (DataAccessException ex)
                    {
                        unit.Rollback();
                        throw ExceptionHelper.ThrowServiceException(ex.Message);
                    }
                }

            }
            else
            {
                using (var unit = DbFactory.UnitOfWork)
                {
                    try
                    {
                        var rep = unit.WfFormType;
                        entity = rep.Find(model.ID);
                        entity.Name = model.Name;
                        entity.ParentID = model.ParentID;
                        entity.SortNumber = model.SortNumber;
                        entity.CompanyID = model.CompanyID;
                        entity.IsDisabled = model.IsDisabled;
                        entity.Remark = model.Remark;

                        unit.BeginTransaction();
                        rep.EntityModified(entity);

                        var msg = new string[] { "修改成功!", "修改失败!" };
                        var result = new OperationResult(unit.Commit() > 0, msg);
                        if (result.Success)
                        {
                            result.Data = new
                            {
                                state = "update",
                                newObj = new
                                {
                                    id = entity.ID,
                                    text = entity.Name,
                                    attributes = new { ParentID = entity.ParentID }
                                }
                            };
                        }
                        return result.SerializeToJsonResult();
                    }
                    catch (DataAccessException ex)
                    {
                        unit.Rollback();
                        throw ExceptionHelper.ThrowServiceException(ex.Message);
                    }
                }



                return this.Update(entity).SerializeToJsonResult();
            }
        }

        /// <summary>
        /// 删除表单类型
        /// </summary>
        /// <param name="id">表单类型ID</param>
        /// <returns></returns>
        public JsonResult RemoveFormType(int id)
        {
            WfFormType entity = this.GetByKey(id);
            if (entity == null) { return new OperationResult(false, true, "表单类型不存在！").SerializeToJsonResult(); }

            using (var unit = DbFactory.UnitOfWork)
            {
                var rep = unit.WfFormType;
                if (rep.SonExist(entity.ID))
                {
                    return new OperationResult(false, "该表单类型下存在子类型，无法删除！").SerializeToJsonResult();
                }

                try
                {
                    unit.BeginTransaction();
                    rep.EntityDeleted(entity);
                    var msg = new string[] { "删除成功!", "删除失败!" };
                    return new OperationResult(unit.Commit() > 0, msg).SerializeToJsonResult();
                }
                catch (DataAccessException ex)
                {
                    unit.Rollback();
                    throw ExceptionHelper.ThrowServiceException(ex.Message);
                }
            }
        }

        #endregion
    }
}
